package cn.dai.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

/**
 * @author ArkD42
 * @file Rbac
 * @create 2020 - 06 - 11 - 9:24
 */
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String act = req.getParameter("act");

        Class<? extends BaseServlet> subClass = this.getClass();

        try {
            BaseServlet subServlet = subClass.newInstance();

            Method declaredMethod = subClass.getDeclaredMethod(act, HttpServletRequest.class, HttpServletResponse.class);

            Object invoke = declaredMethod.invoke(subServlet, req, resp);

            if (invoke instanceof String)  {
                String url = (String)invoke;
                // 我希望不管是转发和重定向，我的方法不想再写这些重复事情, 重定向和转发都应该可以使用
                if (url.contains("forward:")) {
                    req.getRequestDispatcher(url.substring(8)).forward(req,resp);
                    return;
                }
                else if (url.contains("redirect:")) {
                    resp.sendRedirect(req.getContextPath() + url.substring(9));
                    return;
                }
                // 如果上面都不写我就默认是转发处理
                req.getRequestDispatcher(url).forward(req,resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
            // 请求处理发生了异常，应该跳转到一个专门的错误页
            req.setAttribute("exception",e);
            req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
